﻿using MediatR;
using T.Vehicleservice.Domain.Dtos;
using T.Vehicleservice.Domain.T.Vehicleservice.Model;
using T.Vehicleservice.Read.API.Application.Command.ExpenseCommand;
using T.Vehicleservice.Repository.ImpI;
using T.Vehicleservice.Repository.Interface;

namespace T.Vehicleservice.Read.API.Application.CommandHandlers.ExpenseCommandHandler
{
    public class ExpenseShowHandlerCommand : IRequestHandler<ExpenseShowCommand, PageDto<ExpenseRecord>>
    {
        IExpenseRecordRepository expenseRecordRepository;

        public ExpenseShowHandlerCommand(IExpenseRecordRepository expenseRecordRepository)
        {
            this.expenseRecordRepository = expenseRecordRepository;
        }

        public async Task<PageDto<ExpenseRecord>> Handle(ExpenseShowCommand request, CancellationToken cancellationToken)
        {
            var res = await expenseRecordRepository.GetAsync(o => o.IsDeleted == false);
            if (!string.IsNullOrEmpty(request.ExpenseHead))
            {
                res = res.Where(o => o.ExpenseHead.Contains(request.ExpenseHead)).ToList();
            }
            if (!string.IsNullOrEmpty(request.LicensePlateNumber))
            {
                res = res.Where(o => o.LicensePlateNumber.Contains(request.LicensePlateNumber)).ToList();
            }
            if (request.ExpenseDate != null)
            {
                res = res.Where(o => o.ExpenseDate == request.ExpenseDate).ToList();
            }
            if (request.Pageindex == null)
            {
                request.Pageindex = 1;
            }
            if (!string.IsNullOrEmpty(request.CompanyID))
            {
                res = res.Where(o => o.CompanyID == request.CompanyID).ToList();
            }
            if (request.Pagesize == null)
            {
                request.Pagesize = res.Count();
            }
            PageDto<ExpenseRecord> pageDto = new PageDto<ExpenseRecord>();
            pageDto.TotalCount = res.Count();

            pageDto.PageCount = (int)Math.Ceiling(pageDto.TotalCount * 1.0 / (int)request.Pagesize);
            pageDto.list = res.OrderByDescending(o => o.ExpenseId).Skip((int)(request.Pageindex - 1) * (int)request.Pagesize).Take((int)request.Pagesize).ToList();
            return pageDto;
        }
    }
}
